package com.yunao.commons.metasearch.ms;

import com.yunao.commons.metasearch.entity.CatchResult;
import com.yunao.commons.metasearch.entity.CatchResults;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.zip.GZIPInputStream;



public class Sina implements Weibo {
	
	

	public Sina() {

	}
	public CatchResults query(String word, int page, String media) throws Exception {

		//System.out.println("正在查询sina");
		Map<String, T> tMap = R.mspf.get("weibo");
		T ts = tMap.get("sina");

		 word=word.replace("+", " ");
		 word=word.replace("|", "~");
		 word=word.replace("-", " -");
		 System.out.println("sina weibo 运算符转换完成");
		if(page==0)
			page=1;
		word = (ts.url_word_encode == null || "unencode".equals(ts.url_word_encode)) ? word : URLEncoder.encode(
				word, ts.url_word_encode);
		
		//System.out.println("WORD:"+word);

		
		
		
		
		CatchResults CatchResults = new CatchResults();
		Date currDate = new Date();
	
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyMMdd HHmmss");

			String links =ts.url_base+"&"+ts.url_page;
			
			if (word != null  && page >= 1)
				// 替换关键词与页数
				links = links.replace("%word%", word).replace("%page%", String.valueOf(page));
			else
				return CatchResults;
			URL url = new URL(links);
		

			
		
			//System.out.println(links);

			URLConnection conn = url.openConnection();
			// 代理授权
		//	if (T.proxy)
				conn.setRequestProperty("Proxy-Authorization",ts.authorization);
				conn.setConnectTimeout(20000);
				conn.setReadTimeout(20000);
			 //页面经 GZIP 压缩，不这样取可能有乱码
				
			InputStream in =null;
			try{
			in=new GZIPInputStream(conn.getInputStream());
			}
			catch(Exception e)
			{
				System.out.println("代理连接失败"+e);
			//	in.close();
			return null;
			}
			
			BufferedReader bufr = new BufferedReader(new InputStreamReader(in,"utf8"));
			String line;
			StringBuilder sBuilder = new StringBuilder();
			try{
			while ((line = bufr.readLine()) != null)
			{

				sBuilder.append(line);
			}
			}
			catch(Exception e)
			{
				System.out.println("读取数据时，新浪微博发生异常");
				bufr.close();
				in.close();
				return null;
			}
			bufr.close();
			in.close();
			JSONObject result = null;
			try {
				//System.out.println(sBuilder);

				result = JSONObject.fromObject(sBuilder.toString());
			} catch (Exception e) {
				System.out.println("json解析异常"+word);


			}
			//System.out.println("数据："+sBuilder);

			if (result == null)
				return CatchResults;
			JSONArray array =null;
			try{
				array= result.getJSONArray("statuses");
			}
			catch(Exception e)
			{
				return CatchResults;
			}
			if (array == null || array.size() == 0)
				return CatchResults;
			CatchResults.setTotal(result.getInt("total_number"));
			SimpleDateFormat enDateFormat = new SimpleDateFormat("EEE MMM dd HH:mm:ss Z yyyy", Locale.ENGLISH);
			for (int i = 0; i < array.size(); i++) {
				JSONObject item = array.getJSONObject(i);
				CatchResult CatchResult = new CatchResult();
				Date d;
				try {
					d = enDateFormat.parse(item.getString("created_at"));
				} catch (Exception e) {
					d = currDate;
				}
				
				CatchResult.setQ(d.getTime());
				//System.out.println("time:"+d.getTime());
				//CatchResult.setPubdate(dateFormat.format(currDate));
				
				//CatchResult.setSp("one");
				//System.out.println(Thread.currentThread().getStackTrace()[2]+T.cc);
				//CatchResult.setCc(T.cc);
				//CatchResult.setDl(T.dl);
				//System.out.println("updateing"+word);
				CatchResult.setSummary(item.getString("text").replace(URLDecoder.decode(word, "utf8"), "<font color=#ff0000>"+URLDecoder.decode(word, "utf8")+"</font>"));
				JSONObject user = item.getJSONObject("user");
				CatchResult.setLinks("http://weibo.com/" + user.getString("profile_url"));
				CatchResult.setHref("http://weibo.com/" + user.getString("id") + "/"
						+ Base62Util.mid2url(item.getString("mid")));
				CatchResult.setAvatar(user.getString("avatar_hd"));
				//System.out.println(user.getString("name"));
				CatchResult.setAuthor(user.getString("name"));
				CatchResult.setName(ts.name);
				CatchResult.setRepeat(item.getString("reposts_count"));
				CatchResult.setReply(item.getString("comments_count"));
				CatchResult.setSource(item.getString("source"));
			
				JSONArray pics =item.getJSONArray("pic_ids");
				int mediatype=0;
				if(media==null)
					mediatype=0;
				else
				 mediatype=Integer.parseInt(media);
				if(!item.has("thumbnail_pic")&&mediatype!=0)
					continue;

				if(!pics.isEmpty()&&pics.size()>=2)
				{
			          // System.out.println("values:>1"+pics.size());

			           
			                for(int j=0;j<pics.size();j++)
			                {
			                String value = pics.getString(j);  
			            
			                
			                  
			    				CatchResult.getImgs().add("http://ww4.sinaimg.cn/thumbnail/"+value);

			                }

			          
				
				}
				else
				{
					if(item.has("thumbnail_pic"))
					{
					CatchResult.setImg(item.getString("thumbnail_pic"));
					
					}
				}
			
				
				
				
				
				
				
				
				
				//CatchResult.setHo("weibo.com");
				long ctm = System.currentTimeMillis();
      
				parseDate(CatchResult,ctm,d.getTime()+"");
				
				CatchResults.add(CatchResult);
			}
		
		return CatchResults;
	}
	private void parseDate(CatchResult CatchResult, long t, String pubdate) {

		if (pubdate == null || pubdate.length() == 0)
			return;
		Pattern pattern = Pattern.compile("[\\u4e00-\\u9fa5]+");
		Matcher matcher = pattern.matcher(pubdate);
		// 包含中文时
		if (matcher.find()) {
			CatchResult.setPubdate(pubdate);
			

			return;
		}
		long rq = 0;
		try {
			rq = Long.parseLong((pubdate.length() == 10) ? pubdate + "000" : pubdate);
		} catch (Exception e) {
			if (pubdate.length() == 10) {
				SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
				try {
					rq = dateFormat.parse(pubdate).getTime();
				} catch (Exception ex) {

				}
			} else if (pubdate.length() == 16) {
				SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
				try {
					rq = dateFormat.parse(pubdate).getTime();
				} catch (Exception ex) {

				}
			}
		}
Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY, 0);
        cal.set(Calendar.SECOND, 0);
        cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.MILLISECOND, 0);

long todayzero=cal.getTimeInMillis();
CatchResult.setQ(rq);
long i = (t-rq) / 1000;
long j=(t-todayzero)/1000;
  if (i < 60) {
			if(i<=0)
			{
				SimpleDateFormat dateFormat = new SimpleDateFormat("M月d日 HH:mm");
				CatchResult.setPubdate(dateFormat.format(new Date(rq)));
			}
			else
			CatchResult.setPubdate(i + "秒前");
		} else if (i < 60 * 60) {
			CatchResult.setPubdate(i / 60 + "分钟前");
		} else if (i < j) {
			SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm");
			CatchResult.setPubdate("今天 " + dateFormat.format(new Date(rq)));
		} else if (i < 24 * 60 * 60+j) {
			SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm");
			CatchResult.setPubdate("昨天 " + dateFormat.format(new Date(rq)));
		} else {
			SimpleDateFormat dateFormat = new SimpleDateFormat("M月d日 HH:mm");
			CatchResult.setPubdate(dateFormat.format(new Date(rq)));
		}
	}
	public static void main() throws Exception
	{
		Sina sina=new Sina();
		sina.query("北京", 1,"0");
	}

}
